package cn.zmit.kuxi.holder;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.security.auth.PrivateCredentialPermission;

import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.holder.ViewHolderBase;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.BaseActivity;
import cn.zmit.kuxi.activity.ShoppingCartsActivity;
import cn.zmit.kuxi.activity.UserActivity;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.entity.ShoppingCartsEntity;
import cn.zmit.kuxi.image.ImageDisplayer;
import cn.zmit.kuxi.interfaces.OnCartsAddNumListener;
import cn.zmit.kuxi.interfaces.OnItemSelectListener;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.CheckBoxWithListVview;
import cn.zmit.kuxi.widget.CheckBoxWithListVview.OnCheckedChangeListener;

/** * @author chenxu @parameter * @return */
public class ShoppingCartsHorlder extends ViewHolderBase<ShoppingCartsEntity> {
	private Context context;
	private TextView title, goodsName, joinNeed;
	private TextView countDate;
	private ProgressBar progressBar;
	private ImageView goodsPic;
	private CheckBoxWithListVview cb_select;
	private LinearLayout llRoot;
	private RelativeLayout rlRoot, rlChange;
	private Button reduction, add;
	String userid;
	Dialog dialog;
	int dialogNum = 0;
	int num;
	String newNumber;
	int type = 0;
	int newnumber;
	EditText cont;
	public static OnItemSelectListener<ShoppingCartsEntity> onItemSelectListener;
	public static OnCartsAddNumListener<ShoppingCartsEntity> onCartsAddNumListener;
	private LinearLayout ll_rootcheck;
	private TextView tv_already;

	@SuppressLint("InflateParams")
	@Override
	public View createView(LayoutInflater layoutInflater) {
		context = layoutInflater.getContext();
		View view = layoutInflater.inflate(R.layout.item_shoppingcart, null);
		title = (TextView) view.findViewById(R.id.tv_tilte);
		goodsName = (TextView) view.findViewById(R.id.tv_tilte_data);
		progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
		joinNeed = (TextView) view.findViewById(R.id.tv_all_need);
		reduction = (Button) view.findViewById(R.id.btn_reduction);
		countDate = (TextView) view.findViewById(R.id.tv_count);
		add = (Button) view.findViewById(R.id.btn_add);
		goodsPic = (ImageView) view.findViewById(R.id.img_product);
		llRoot = (LinearLayout) view.findViewById(R.id.llRoot);
		rlRoot = (RelativeLayout) view.findViewById(R.id.rl_selectOne);
		title = (TextView) view.findViewById(R.id.tv_tilte);
		tv_already = (TextView) view.findViewById(R.id.tv_already);
		ll_rootcheck = (LinearLayout) view.findViewById(R.id.ll_rootcheck);
		rlChange = (RelativeLayout) view.findViewById(R.id.rl_change_num);
		cb_select = (CheckBoxWithListVview) view.findViewById(R.id.cb_select);
		Boolean hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			userid = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}
		if (Constants.TYPE == 1) {// 用于判断checkBox是否显示
			cb_select.setVisibility(View.VISIBLE);
			ll_rootcheck.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					cb_select.setChecked(!cb_select.isChecked());
				}
			});
		} else {

			cb_select.setVisibility(View.GONE);
		}
		return view;
	}

	private static boolean isMatch(String regex, String orginal) {
		if (orginal == null || orginal.trim().equals("")) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher isNum = pattern.matcher(orginal);
		return isNum.matches();
	}

	public static boolean isPositiveInteger(String orginal) {
		return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
	}

	@Override
	public void showData(final int position, final ShoppingCartsEntity itemData) {
		if (itemData.getPicUrl() != null && itemData.getPicUrl().length() > 0) {
			ImageDisplayer.getInstance().dispalyImageWithRadius(
					Url.IMAGE_PICTURES + itemData.getPicUrl(), goodsPic, 0);
		} else {
			goodsPic.setImageResource(R.drawable.ic_launcher);
		}
		if (type == 0) {
			countDate.setText(itemData.getGoodsNum());
		} else {
			String text = countDate.getText().toString().trim();
			countDate.setText(text);
		}
		num = Integer.parseInt(itemData.getGoodsNum());

		title.setText("第" + itemData.getTitle() + "期");
		goodsName.setText(itemData.getGoodsName());
		double all = Integer.parseInt(itemData.getJoinNeed());
		double join = Integer.parseInt(itemData.getJoinCount());
		final double result = ((join / all) * 100);
		progressBar.setMax(100);
		progressBar.setProgress((int) (result));
		joinNeed.setText("总需人数：" + itemData.getJoinNeed());
		tv_already.setText("已参与：" + itemData.getJoinCount());

		countDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = new Dialog(context, R.style.MyDialogStyleBottom);
				View view = View.inflate(context,
						R.layout.dialog_shopping_carts, null);
				cont = (EditText) view.findViewById(R.id.edit_dialog_count);
				Button reduceButton = (Button) view
						.findViewById(R.id.btn_dialog_reduction);
				Button addButton = (Button) view
						.findViewById(R.id.btn_dialog_add);
				cont.setText(itemData.getGoodsNum());
				cont.setSelection(itemData.getGoodsNum().length());
				LinearLayout cancle = (LinearLayout) view
						.findViewById(R.id.ll_cancle);
				LinearLayout ok = (LinearLayout) view.findViewById(R.id.ll_ok);
				ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (onCartsAddNumListener != null) {

							if ((!TextUtils.isEmpty(cont.getText().toString()
									.trim()))
									&& isPositiveInteger(cont.getText()
											.toString().trim())) {
								dialogNum = Integer.parseInt(cont.getText()
										.toString().trim());
								onCartsAddNumListener.onlistItemSelect(
										position, itemData, dialogNum);
								dialog.dismiss();
							} else {
								Toast.makeText(context, "非法输入", 0).show();
							}
						}
					}
				});
				cancle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				reduceButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int oldQuantity = 0;
						oldQuantity = Integer.parseInt(cont.getText()
								.toString().trim());

						if (oldQuantity <= 1) {
							ToastUtils.show(context, "购买数量不能小于1");
							return;
						}
						dialogNum = oldQuantity - 1;
						cont.setText(dialogNum + "");
						cont.setSelection((dialogNum + "").length());
					}
				});
				addButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int oldnum = 0;
						oldnum = Integer.parseInt(cont.getText().toString()
								.trim());

						dialogNum = oldnum + 1;
						cont.setText(dialogNum + "");
						cont.setSelection((dialogNum + "").length());
					}
				});
				dialog.setContentView(view);
				dialog.show();
				// cont获得焦点弹出键盘
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						InputMethodManager m = (InputMethodManager) cont
								.getContext().getSystemService(
										Context.INPUT_METHOD_SERVICE);
						m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					}
				}, 300);

				cont.setInputType(EditorInfo.TYPE_CLASS_PHONE);

			}
		});

		reduction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int oldQuantity = 0;
				oldQuantity = Integer.parseInt(countDate.getText().toString()
						.trim());
				int newQuantity = 0;
				if (oldQuantity <= 1) {
					ToastUtils.show(context, "购买数量不能小于1");
					return;
				}
				newQuantity = oldQuantity - 1;
				// updateCartQuantity(itemData, newQuantity);
				if (onCartsAddNumListener != null) {
					onCartsAddNumListener.onlistItemSelect(position, itemData,
							newQuantity);
				}
			}
		});
		add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				int oldnum = 0;
				oldnum = Integer
						.parseInt(countDate.getText().toString().trim());

				int addnum = 0;
				addnum = oldnum + 1;
				if (onCartsAddNumListener != null) {

					onCartsAddNumListener.onlistItemSelect(position, itemData,
							addnum);
				}
			}
		});

		if (ShoppingCartsActivity.mSelectItemList != null
				&& ShoppingCartsActivity.mSelectItemList.contains(itemData)) {
			cb_select.updateState(true);

		} else {
			cb_select.updateState(false);
		}

		cb_select.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CheckBoxWithListVview checkBox,
					boolean isChecked) {
				onItemSelectListener
						.onItemSelect(position, itemData, isChecked);
			}
		});

	}

	public void updateCartQuantity(final ShoppingCartsEntity itemData,
			final int newQuantity) {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("gp_id", itemData.getGp_id());
		map.put("user_id", userid);
		map.put("portion", newQuantity + "");
		// System.out.println("))))))))))))))))))))))))))))"+gp_id+"&&&&&&&&&&&&&&&"+id+"**********************"+newQuantity+"***************************************");
		RequestTask.getInstance().doAdd(context, map,
				new OnRequestListenerAdapter<Object>() {
					@Override
					public void onDone(XDroidRequest<?> request,
							String response, DataType dataType) {
						super.onDone(request, response, dataType);
						JsonData jsonData = JsonData.create(response);
						String data = jsonData.optString("code");
						// countDate.setText("");
						num = newQuantity;
						if (data != null && data.equals("0")) {
							countDate.setText(num + "");
							type = 0;
							// ToastUtils.show(context,
							// jsonData.optString("message"));
						} else {
							// ToastUtils.show(context,
							// jsonData.optString("message"));
						}

					}

				});

	}

	// 设置接口回掉
	public static void setOnItemSelectListener(
			OnItemSelectListener<ShoppingCartsEntity> onItemSelectListener) {
		ShoppingCartsHorlder.onItemSelectListener = onItemSelectListener;
	}

	public static void setListener(
			OnCartsAddNumListener<ShoppingCartsEntity> onCartsAddNumListener) {
		ShoppingCartsHorlder.onCartsAddNumListener = onCartsAddNumListener;
	}

}
